import axios from "axios";

const http=axios.create({
    // baseURL: process.env.VUE_APP_BASE_API,
    timeout: 7000,
    headers: {
        'content-type': 'application/json',
        
    },
    withCredentials: true
});
http.defaults.withCredentials=true;



//请求前拦截
http.interceptors.request.use(req=>{
    let current_authorization=sessionStorage.getItem("current_authorization");
    let refresh_authorization=sessionStorage.getItem("refresh_authorization");
    if(current_authorization&&refresh_authorization){
        req.headers['current_authorization']=current_authorization;
        req.headers['refresh_authorization']=refresh_authorization;
    }
    return req
},err=>{
    return Promise.reject(err)
});

//响应拦截
http.interceptors.response.use(resp=>{
    if([1005,1006,1007].indexOf(resp.data.code)!=-1){
        window.location.href="/#/login"
        sessionStorage.removeItem("loginUser");
        sessionStorage.removeItem("current_authorization");
        sessionStorage.removeItem("refresh_authorization");
    }
    if(resp.headers['current_authorization']){
        sessionStorage.setItem("current_authorization",resp.headers['current_authorization'])
    }
    if(resp.headers['refresh_authorization']){
        sessionStorage.setItem("refresh_authorization",resp.headers['refresh_authorization'])
    }
    return resp
},err=>{
    if(err.response.status==401){
        //重新登录
        window.location.href="/#/login"
        sessionStorage.removeItem("loginUser");
        //移除sessionStorage的token
        sessionStorage.removeItem("current_authorization");
        sessionStorage.removeItem("refresh_authorization");
    }
    return Promise.reject(err)
})

export default http;
